from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from web import models
from web.forms.wiki import WikiForm
from utils.encrypt import uid
from utils.tencent.cos import  upload_file


def wiki(request, project_id):
    """ wiki的首页 """
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()

    return render(request, 'wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    """ wiki添加 """
    if request.method == 'GET':
        form = WikiForm(request)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiForm(request, data=request.POST)
    if form.is_valid():
        # 判断用户是否已经选择父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)

    return render(request, 'wiki_form.html', {'form': form})


def wiki_catalog(request, project_id):
    """ wiki目录 """

    # 获取当前项目所有的目录: data = QuerySet类型
    # data = models.Wiki.objects.filter(project=request.tracer.project).values_list("id", 'title', 'parent_id')
    data = models.Wiki.objects.filter(project=request.tracer.project).values("id", 'title', 'parent_id').order_by(
        'depth', 'id')
    # data = models.Wiki.objects.filter(project=request.tracer.project).values("id", 'title', 'parent_id')
    return JsonResponse({'status': True, 'data': list(data)})


def wiki_delete(request, project_id, wiki_id):
    """ 删除文章 """

    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()

    url = reverse('wiki', kwargs={'project_id': project_id})
    return redirect(url)


def wiki_edit(request,project_id,wiki_id):
    """编辑文章"""
    wiki_object  = models.Wiki.objects.filter(project_id=project_id,id=wiki_id).first()
    if not wiki_object:
        url = reverse('wiki',kwargs={'project_id':project_id})
        return  redirect(url)

    if request.method == "GET":

        form = WikiForm(request,instance=wiki_object)

        return   render(request, 'wiki_form.html', {'form': form})

    form = WikiForm(request,data=request.POST,instance=wiki_object)
    if form.is_valid():
        # 判断用户是否已经选择父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()


        # 这url? wtf?
        url = reverse('wiki', kwargs={'project_id': project_id})
        preview_url = "{0}?wiki_id={1}".format(url, wiki_id)
        return redirect(preview_url)




# def wiki_upload(request,project_id,):
#     #此处会失败 报错 Forbidden (CSRF token missing or incorrect.): /manage/1/wiki/upload/
#     #因为 markdown 此时传文件时 使用了post请求 而为携带csrf_token
#     return JsonResponse({'status':'copy'})

#免除csrf_token检测
@csrf_exempt
def wiki_upload(request,project_id):

    # print('copy')
    img_obj = request.FILES.get('editormd-image-file')

    #将文件对象 上传到当前项目的桶中
    # Bucket = request.tracer.project.bucket

    #重命名用户上传的文件名 防止COS  中重名覆盖掉
    # print(img_obj.name)
    result = {
        'success': 0,
        'message': None,
        'url': None
    }

    if not img_obj:
        result['message'] = "文件不存在"
        return JsonResponse(result)

    ext = img_obj.name.rsplit('.')[-1]#即上传的格式结尾

    # print(ext)
    key = "{}.{}".format(uid(request.tracer.user.mobile_phone), ext)

    print(key)
    #"""小于分块大小的的文件简单上传，大于等于分块大小的文件使用分块上传
    image_url = upload_file(
        request.tracer.project.bucket,
        request.tracer.project.region,
        img_obj,
        key,
    )
    print('os ok 001')
    result['success'] = 1
    result['url'] = image_url
    # 回传COS中 当前文件的URL  以供markdown显示  保存
    # 通知markdown editor
    return JsonResponse(result)





